package com.zxc.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zxc.common.constant.CartConstant;
import com.zxc.common.exception.NoStockException;
import com.zxc.common.to.OrderTo;
import com.zxc.common.to.SkuStockTo;
import com.zxc.common.to.mq.SeckillOrderTo;
import com.zxc.common.utils.R;
import com.zxc.common.vo.MemberRespVo;
import com.zxc.gulimall.order.constant.OrderConstant;
import com.zxc.gulimall.order.constant.PayConstant;
import com.zxc.gulimall.order.dao.OrderItemDao;
import com.zxc.gulimall.order.entity.OrderItemEntity;
import com.zxc.gulimall.order.entity.PaymentInfoEntity;
import com.zxc.gulimall.order.enume.OrderStatusEnum;
import com.zxc.gulimall.order.feign.CartFeignService;
import com.zxc.gulimall.order.feign.MemberFeignService;
import com.zxc.gulimall.order.feign.ProductFeignService;
import com.zxc.gulimall.order.feign.WmsFeignService;
import com.zxc.gulimall.order.interceptor.LoginUserInterceptor;
import com.zxc.gulimall.order.service.OrderItemService;
import com.zxc.gulimall.order.service.PaymentInfoService;
import com.zxc.gulimall.order.to.OrderCreateTo;
import com.zxc.gulimall.order.to.SpuInfoVo;
import com.zxc.gulimall.order.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxc.common.utils.PageUtils;
import com.zxc.common.utils.Query;

import com.zxc.gulimall.order.dao.OrderDao;
import com.zxc.gulimall.order.entity.OrderEntity;
import com.zxc.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> submitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1、feign远程调用会丢失掉请求头的一些参数   2、使用线程池进行异步编排会导致无法获取用户的信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、远程调用会员服务，获取所有收货地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        },executor);


        CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);

            //2、远程查询购物车选中的购物项
            List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
            orderConfirmVo.setItems(currentUserCartItem);
        },executor).thenRunAsync(()->{
            //加入线程池是可以加块程序的执行，但是也会带来各种问题，这里如果不添加请求头的cookie远程调用玩之后就会丢失掉我们的cookie数据
            //导致被我们订单服务的Feign拦截器给拦截到
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIdList = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R r = wmsFeignService.hasStock(skuIdList);
            if (r.getCode() == 0){
                List<SkuStockTo> skuHashStock = r.getData(new TypeReference<List<SkuStockTo>>() {
                });
                if (skuHashStock != null){
                    Map<Long, Boolean> collect = skuHashStock.stream().collect(Collectors.toMap(SkuStockTo::getSkuId, SkuStockTo::getHasStock));
                    orderConfirmVo.setSkuStocks(collect);
                }
            }

        },executor);


        //3、优惠券信息，我们存用户积分信息
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4、其他数据自动计算

        //5、防重复令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(future1,future2).get();

        return orderConfirmVo;
    }

    /*下单*/
    //@GlobalTransactional//全局事务
    @Transactional
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo vo) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderSubmitRespVo orderSubmitRespVo = new OrderSubmitRespVo();
        orderSubmitRespVo.setCode(0);
        submitVoThreadLocal.set(vo);//保存用户提交的
        //下单：===》》》创建订单，验令牌，验价格，锁库存。。。
        //1、验证令牌【令牌的对比和删除得保证原子性】
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        //通过lure脚本原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                orderToken);
        if (result == 0L){
            //验证失败
            orderSubmitRespVo.setCode(1);
            return orderSubmitRespVo;
        }else {
            //验证成功 验价格，锁库存。。。
            //1、创建订单和订单项信息
            OrderCreateTo orderCreateTo = createOrder();
            //2、验价
            BigDecimal payAmount = orderCreateTo.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                //金额对比成功
                //将订单数据放入数据库，保存订单
                saveOrder(orderCreateTo);
                //锁定库存，只要有异常回滚订单数据。
                // 订单号，所有订单项（skuId，num（数量），skuName）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(orderCreateTo.getOrder().getOrderSn());

                List<OrderItemVo> collect = orderCreateTo.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(collect);

                //远程锁定库存
                R r = wmsFeignService.orderLockStock(lockVo);

                if (r.getCode() == 0){
                    //锁成功了
                    //远程扣积分
                    orderSubmitRespVo.setOrder(orderCreateTo.getOrder());

                    //订单创建完成发送消息给MQ
                    log.info("下单成功，发送消息，创建订单......");
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateTo.getOrder());

                    log.info("下单成功，删除redis中购物车商品记录......");
                    //删除购物车里的数据
                    stringRedisTemplate.delete(CartConstant.CART_PREFIX +memberRespVo.getId());

                    return orderSubmitRespVo;
                }else {
                    //锁失败了
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }


            }else {
                //金额对比失败
                orderSubmitRespVo.setCode(1);
                return orderSubmitRespVo;
            }
        }

        /* String redisToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
        if (orderToken != null && orderToken.equals(redisToken)){
            //令牌验证通过

            return orderSubmitRespVo;
        }else {
            //验证不通过
        }*/
    }

    @Override
    public OrderEntity getOrderDetailByOrderSn(String orderSn) {
        OrderEntity orderEntity = this.baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    //取消订单
    @Override
    public void closeOrder(OrderEntity orderEntity) {
        //关闭订单之前，查询订单的最新状态
        OrderEntity byId = this.getById(orderEntity.getId());
        //待付款
        if (byId.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()){
            //关单，修改订单状态为取消付款
            OrderEntity updateOrderEntity = new OrderEntity();
            updateOrderEntity.setId(byId.getId());
            updateOrderEntity.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(updateOrderEntity);//修改订单状态
            log.info("订单过期，取消订单成功......");
            //发送一个取消订单消息给消息队列
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);

            //TODO 保证消息一定会发送出去，做好日志记录（给数据库保存每一个消息的详细信息）
            //TODO 定期扫描数据库，将失败的消息再发送一遍
            try {
                log.info("订单取消成功，发送消息给消息队列解锁库存......");
                rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
            }catch (Exception e){
                //将没发送成功的消息重试发送
            }
        }

    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        OrderEntity orderDetailByOrderSn = this.getOrderDetailByOrderSn(orderSn);//订单详情

        List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = orderItemEntities.get(0);
        BigDecimal payAmount = orderDetailByOrderSn.getPayAmount().setScale(2, BigDecimal.ROUND_UP);//小数点两位,向上取值

        PayVo payVo = new PayVo();
        payVo.setBody(orderItemEntity.getSkuAttrsVals());//订单备注
        payVo.setOut_trade_no(orderDetailByOrderSn.getOrderSn());//订单号
        payVo.setSubject(orderItemEntity.getSkuName());//订单主体
        payVo.setTotal_amount(payAmount.toString());//订单价格

        return payVo;
    }

    /*
    * 查询当前登录用户的所有订单信息
    * */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                //降序拿到最新的订单
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("order_sn")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItems(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    /*
    * 处理支付宝的支付结果
    * */
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        //1、保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(vo.getTrade_no());
        paymentInfoEntity.setOrderSn(vo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(vo.getTrade_status());
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        //修改订单状态
        //获取当前状态
        String tradeStatus = vo.getTrade_status();

        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = vo.getOut_trade_no(); //获取订单号
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode(), PayConstant.ALIPAY);
        }

        return "success";
    }

    //创建秒杀订单信息
    @Override
    public void createSkillOrder(SeckillOrderTo seckillOrderTo) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //价格 == 秒杀价格*秒杀数量
        BigDecimal bigDecimal = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(bigDecimal);

        //订单信息补充
        orderEntity.setCreateTime(new Date());
        //运费。。。

        //保存订单信息
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(orderEntity.getOrderSn());
        orderItemEntity.setRealAmount(bigDecimal);
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(orderItemEntity);
        log.info("秒杀订单创建成功，等待用户付款！");
    }

    /*
    * 保存订单数据到数据库
    * */
    private void saveOrder(OrderCreateTo orderCreateTo) {
        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        for (OrderItemEntity orderItemEntity : orderItems){
            orderItemService.save(orderItemEntity);
        }
    }

    private OrderCreateTo createOrder(){
        OrderCreateTo createTo = new OrderCreateTo();
        //生成订单号
        String orderSn = IdWorker.getTimeId();
        //1、创建订单实体列
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);

        //3、验价(计算价格相关)
        computerPrice(orderEntity,orderItemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(orderItemEntities);

        return createTo;
    }

    /*
    * 计算价格
    * */
    private void computerPrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    //构建订单
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());

        //设置订单状态为0代付款
        orderEntity.setStatus(0);

        //获取收获地址信息,远程调用
        OrderSubmitVo orderSubmitVo = submitVoThreadLocal.get();
        R fare = wmsFeignService.getFare(orderSubmitVo.getAddrId()); //地址和邮费信息
        FareVo data = fare.getData(new TypeReference<FareVo>() {});
        BigDecimal fare1 = data.getFare();
        //设置运费信息
        orderEntity.setFreightAmount(fare1);
        //设置收货人信息
        orderEntity.setReceiverCity(data.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        orderEntity.setReceiverName(data.getAddress().getName());
        orderEntity.setReceiverPhone(data.getAddress().getPhone());
        orderEntity.setReceiverPostCode(data.getAddress().getPostCode());
        orderEntity.setReceiverProvince(data.getAddress().getProvince());
        orderEntity.setReceiverRegion(data.getAddress().getRegion());
        return orderEntity;
    }

    //构建所有订单项数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每一个购物项的价格
        List<OrderItemVo> currentUserCartItem = cartFeignService.getCurrentUserCartItem();
        if (currentUserCartItem != null && currentUserCartItem.size() > 0){
            List<OrderItemEntity> itemEntities = currentUserCartItem.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = new OrderItemEntity();
                orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    //构建某一个订单项
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息：订单号√
        //2、商品的Spu信息
        Long skuId = cartItem.getSkuId();
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //3、商品的Sku信息√
        orderItemEntity.setSkuId(cartItem.getSkuId());
        orderItemEntity.setSkuName(cartItem.getTitle());
        orderItemEntity.setSkuPic(cartItem.getImage());
        orderItemEntity.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttr);
        orderItemEntity.setSkuQuantity(cartItem.getCount());
        //4、优惠信息【不做】
        //5、积分信息√
        orderItemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        orderItemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());

        //6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        //当前订单项的实际金额
        BigDecimal realPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        realPrice.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getPromotionAmount()).subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(realPrice);

        return orderItemEntity;

    }

}